package com.ezlcp.form.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ezlcp.commons.base.db.BaseDao;
import com.ezlcp.commons.base.db.BaseService;
import com.ezlcp.commons.constant.StatusEnum;
import com.ezlcp.commons.service.impl.SuperServiceImpl;
import com.ezlcp.commons.tool.StringUtils;
import com.ezlcp.commons.utils.ContextUtil;
import com.ezlcp.form.entity.Module;
import com.ezlcp.form.mapper.ModuleMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.ezlcp.commons.constant.Constants.*;

/**
 * [对创建的实体，表单，流程进行分组]业务服务类
 */
@Service
public class ModuleServiceImpl extends SuperServiceImpl<ModuleMapper, Module> implements BaseService<Module> {
    @Resource
    private ModuleMapper moduleMapper;

    /***
     * @description 选择模块的下拉框数据来源
     * @return java.util.List<com.ezlcp.form.entity.Module>
     * @author Elwin ZHANG
     * @date 2023/4/21 13:08
     */
    public List<Module> selectModule() {
        String tenantId = ContextUtil.getCurrentTenantId();
        QueryWrapper<Module> wrapper = new QueryWrapper<>();
        if (StringUtils.isEmpty(tenantId)) {
            wrapper.and(query -> query.eq(COL_TENANT_ID, "").or().isNull(COL_TENANT_ID));
        } else {
            wrapper.eq(COL_TENANT_ID, tenantId);
        }
        wrapper.eq(COL_STATUS, StatusEnum.enable.getCode());
        wrapper.orderByAsc("level", "sort");
        return moduleMapper.selectList(wrapper);
    }

    /***
     * @description 删除模块
     * @param moduleId 模块ID
     * @author Elwin ZHANG
     * @date 2023/4/20 17:31
     */
    public void deleteModule(String moduleId) {
        var module = moduleMapper.selectById(moduleId);
        if (module == null) {
            return;
        }
        module.setStatus((short) StatusEnum.deleted.getValue());
        module.setSeq(module.getSeq() + 1);
        moduleMapper.updateById(module);
    }

    /***
     * @description 根据当前组的类型返回本企业可选择的父节点
     * @param moduleId 当前模块ID
     * @return java.util.List<com.ezlcp.user.entity.Group>
     * @author Elwin ZHANG
     * @date 2023/3/17 13:44
     */
    public List<Module> selectParent(String moduleId) {
        QueryWrapper<Module> wrapper = new QueryWrapper<>();
        String tenantId = ContextUtil.getCurrentTenantId();
        if (StringUtils.isEmpty(tenantId)) {
            wrapper.and(query -> query.eq(COL_TENANT_ID, "").or().isNull(COL_TENANT_ID));
        } else {
            wrapper.eq(COL_TENANT_ID, tenantId);
        }

        wrapper.eq(COL_STATUS, StatusEnum.enable.getCode());
        if (StringUtils.isNotEmpty(moduleId)) {
            wrapper.ne(COL_MODULE_ID, moduleId);
            wrapper.ne(COL_PARENT_ID, moduleId);
        }
        wrapper.orderByAsc("level", "sort");
        return moduleMapper.selectList(wrapper);
    }

    @Override
    public BaseDao<Module> getRepository() {
        return moduleMapper;
    }
}